package labox.innovation.loginserver.socket;

import java.net.InetAddress;
import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import labox.innovation.config.Config;
import labox.innovation.loginserver.LoginController;
import labox.innovation.loginserver.socket.serverpackets.Init;

import labox.innovation.netcore.IAcceptFilter;
import labox.innovation.netcore.IClientFactory;
import labox.innovation.netcore.IMMOExecutor;
import labox.innovation.netcore.MMOConnection;
import labox.innovation.netcore.ReceivablePacket;

/**
 * 
 * 处理socket连接客户端上行的数据包
 * 
 * @author KenM
 */
public class SelectorHelper extends Thread implements IMMOExecutor<LoginClient>, IClientFactory<LoginClient>, IAcceptFilter {

	private Map<String, Flood> _ipFloodMap;

	/**
	 * 处理登录连接包的线程池
	 */
	private ThreadPoolExecutor _generalPacketsThreadPool;

	public SelectorHelper() {
		_generalPacketsThreadPool = new ThreadPoolExecutor(4, 6, 15L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
		_ipFloodMap = new ConcurrentHashMap<String, Flood>();
		setDaemon(true);
		setPriority(Thread.MIN_PRIORITY);
		start();
	}

	/**
	 * 
	 * @see labox.innovation.netcore.IMMOExecutor#execute(labox.innovation.netcore.ReceivablePacket)
	 */
	public void execute(ReceivablePacket<LoginClient> packet) {
		_generalPacketsThreadPool.execute(packet);
	}

	/**
	 * 
	 * 当有客户端连接上来创建客户端对象，并发送初始化协议
	 */
	public LoginClient create(MMOConnection<LoginClient> con) {
		LoginClient client = new LoginClient(con);
		//加入到为等待授权的队列中
		LoginController.getInstance().addLoginClient(client);
		client.sendPacket(new Init(client));
		return client;
	}

	/**
	 * 检查是否接受客户端的连接
	 */
	public boolean accept(SocketChannel sc) {
		if (Config.FLOOD_PROTECTION_CLIENT) {
			long current = System.currentTimeMillis();
			String addr = sc.socket().getInetAddress().getHostAddress().intern();

			synchronized (addr) {
				Flood f = _ipFloodMap.get(addr);
				if (f != null) {
					f.lastAccess = current;
					if (f.trys > Config.FAST_CONNECTION_LIMIT_CLIENT) {
						return false;
					} else if (current - f.lastAccess < 1000L) {
						f.trys++;
					}
				} else {
					_ipFloodMap.put(addr, new Flood());
				}
			}
		}

		return LoginController.getInstance().acceptAddress(sc.socket().getInetAddress());
	}

	private class Flood {
		long lastAccess;

		int trys;

		Flood() {
			lastAccess = System.currentTimeMillis();
			trys = 0;
		}
	}

	/**
	 * 
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		while (true) {
			long reference = System.currentTimeMillis() - (1000 * 300);
			for (Map.Entry<String, Flood> e : _ipFloodMap.entrySet()) {
				Flood f = e.getValue();
				if (f.lastAccess < reference)
					_ipFloodMap.remove(e.getKey());
			}

			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {

			}
		}
	}
}
